package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApBehaviorServiceImpl implements ApBehaviorService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult loadArticleBehavior(ArticleBehaviorDto dto) {
        if(dto.getArticleId() == null){
            return ResponseResult.okResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        ApUser apUser = ApThreadLocalUtil.getUser();
        if(apUser == null){
            return ResponseResult.okResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if(apUser.getId() == 0){
            return ResponseResult.okResult(405,"请先登录");
        }
        //设置默认值
        Boolean isLike = Boolean.FALSE;
        Boolean isUnlike = Boolean.FALSE;
        Boolean isCollection = Boolean.FALSE;
        Boolean isFollow = Boolean.FALSE;

        //是否点赞
        String likes_key = "USER_LIKES_" + dto.getArticleId();
        isLike = getBehaviorFlag(likes_key, apUser.getId().toString());

        //是否不喜欢
        String unlikes_key = "USER_UNLIKES_" + dto.getArticleId();
        isUnlike = getBehaviorFlag(unlikes_key, apUser.getId().toString());

        //是否收藏
        String collection_key = "USER_COLLECTION_" + dto.getArticleId();
        isCollection = getBehaviorFlag(collection_key, apUser.getId().toString());

        //是否关注
        String follow_key = "USER_FOLLOW_" + apUser.getId();
        isFollow = getBehaviorFlag(follow_key, dto.getAuthorId().toString());

        //封装数据
        Map map = new HashMap();
        map.put("isfollow",isFollow);
        map.put("iscollection",isCollection);
        map.put("isunlike",isUnlike);
        map.put("islike",isLike);
        return ResponseResult.okResult(map);
    }

    /**
     * 从redis查询行为状态
     * @param bigKey
     * @param smallKey
     * @return
     */
    private Boolean getBehaviorFlag(String bigKey,String smallKey) {
        return redisTemplate.opsForHash().hasKey(bigKey,smallKey);
    }
}
